package com.cxyd.modules.wms.excel.listener;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.cxyd.common.exception.RootException;
import com.cxyd.common.utils.ConvertUtils;
import com.cxyd.modules.wms.dto.OrderDTO;
import com.cxyd.modules.wms.dto.OrderDetailDTO;
import com.cxyd.modules.wms.entity.OrderEntity;
import com.cxyd.modules.wms.entity.SpuEntity;
import com.cxyd.modules.wms.excel.easy.OrderEasyExcel;
import com.cxyd.modules.wms.service.OrderDetailService;
import com.cxyd.modules.wms.service.OrderService;
import com.cxyd.modules.wms.service.SpuService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class OrderExcelListener extends AnalysisEventListener<OrderEasyExcel> {

    private static final Logger logger = LoggerFactory.getLogger(OrderExcelListener.class);

    private final OrderService orderService;
    private final OrderDetailService orderDetailService;
    private final SpuService spuService;

    private static final int BATCH_COUNT = 1;
    private List<OrderEasyExcel> cache = new ArrayList<>(BATCH_COUNT);
    private static final String COMMENT = "出库单批量导入";
    private int total = 0;
    private OrderDTO order = new OrderDTO();

    public OrderExcelListener(OrderService orderService, OrderDetailService orderDetailService, SpuService spuService) {
        this.orderService = orderService;
        this.orderDetailService = orderDetailService;
        this.spuService = spuService;
    }

    @Override
    public void invoke(OrderEasyExcel orderEasyExcel, AnalysisContext analysisContext) {
        cache.add(orderEasyExcel);
        if (total == 0) {
            saveOrder();
        }
        if (cache.size() >= BATCH_COUNT) {
            saveDetail();
            cache.clear();
        }
        total++;
    }

    private void saveOrder() {
        OrderEasyExcel orderEasyExcel = cache.get(0);
        if (StrUtil.isEmpty(orderEasyExcel.getSaleNo())) {
            throw new RootException("发货单号不可为空！");
        }
        if (StrUtil.isEmpty(orderEasyExcel.getSupplierName())) {
            throw new RootException("客户简称不可为空！");
        }
        OrderEntity insertOrder = new OrderEntity();
        insertOrder.setOrderNo("OUT#" + orderEasyExcel.getSaleNo());
        insertOrder.setOrderType("销售出库");
        // 销售单号
        insertOrder.setSaleNo(orderEasyExcel.getSaleNo());
        insertOrder.setSupplierName(orderEasyExcel.getSupplierName());
        insertOrder.setOrderSt(0);
        insertOrder.setComments(orderEasyExcel.getComments());
        orderService.insert(insertOrder);
        order = ConvertUtils.sourceToTarget(insertOrder, OrderDTO.class);
    }

    private void saveDetail() {
        for (OrderEasyExcel excel : cache) {
            if (StrUtil.isEmpty(excel.getSpuNo())) {
                throw new RootException("器材代码不可为空！");
            }
            if (excel.getPlanQty().compareTo(BigDecimal.ZERO) <= 0) {
                throw new RootException("件数必须大于0！");
            }
            String spuNo = excel.getSpuNo();
            SpuEntity spuEntity = spuService.findBySpuNo(spuNo);
            if (ObjectUtils.isEmpty(spuEntity)) {
                throw new RootException("所需物料【" + spuNo + "】未在系统中维护!请检查" + "】");
            }
            OrderDetailDTO insertDetail = new OrderDetailDTO();
            insertDetail.setOrderId(order.getOrderId());
            insertDetail.setSpuNo(spuNo);
            insertDetail.setSpuName(spuEntity.getSpuName());
            insertDetail.setPlanQty(excel.getPlanQty());
            insertDetail.setDetailSt(0);
            insertDetail.setComments(COMMENT);
            orderDetailService.save(insertDetail);
        }
        cache.clear();
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveDetail();
        cache.clear();
        logger.info("出库单处理完成 count={}", total);
    }
}
